package dao;

import java.sql.SQLException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import pojo.Cliente;

public class DaoCliente implements Dao<Cliente> {
	
	private EntityManager em;
	
	public DaoCliente(EntityManager em) {
		super();
		this.em=em;
	}
	
	@Override
	public void gravar(Cliente bean) throws SQLException {
		em.getTransaction().begin();
		em.persist(bean);
		em.getTransaction().commit();
	}

	@Override
	public Cliente buscar(String valor) throws SQLException {
		Query q = em.createQuery("SELECT c FROM Cliente c WHERE c.codigo = :id");
		q.setParameter("id", Long.parseLong(valor));
		return (Cliente) q.getSingleResult();
	}

	@Override
	public void excluir(Cliente c) throws SQLException {
		em.getTransaction().begin();
		c=em.find(Cliente.class, c.getCodigo());
		em.remove(c);
		em.getTransaction().commit();	
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cliente> obterLista(Class<Cliente> tipo) throws SQLException {
		Query q = em.createQuery("SELECT c FROM Cliente c");
		return q.getResultList();
	}

	@Override
	public void atualizar(Cliente entidade) throws SQLException {
		em.getTransaction().begin();
		em.merge(entidade);
		em.getTransaction().commit();			
	}

}
